package com.example.dense_rack_server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dense_rack_server.entity.HostTemHum;
import com.example.dense_rack_server.mapper.HostTemHumMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * <p>
 * 温湿度 服务实现类
 * </p>
 *
 * @author 张彬
 * @since 2025-03-18
 */
@Slf4j
@Service
public class HostTemHumService extends ServiceImpl<HostTemHumMapper, HostTemHum> {

    @Resource
    private HostTemHumMapper hostTemHumMapper;

    /**
     * 获取折线图
     * @throws ParseException
     */
    public Map<String, Object> getHostTemHumList(String selectStartDate, String selectEndDate, String hostId) {
        List<String> xNameList = new ArrayList<>();
        List<String> temList = new ArrayList<>();
        List<String> humList = new ArrayList<>();
        List<HostTemHum> list = null;
        if (StrUtil.isEmpty(selectStartDate) && StrUtil.isEmpty(selectEndDate)) {
            Date date = DateUtil.date();
            DateTime beginOfDay = DateUtil.beginOfDay(date);
            QueryWrapper<HostTemHum> queryWrapper = new QueryWrapper<HostTemHum>();
            queryWrapper.ge("create_time", beginOfDay).orderByAsc("create_time").eq("host_id", Convert.toInt(hostId));
            list = hostTemHumMapper.selectList(queryWrapper);

        } else {
            QueryWrapper<HostTemHum> queryWrapper = new QueryWrapper<>();
            Date date = DateUtil.parse(selectStartDate, "yyyy-MM-dd");
            selectStartDate = DateUtil.formatDate(date);

            Date endDate = DateUtil.parse(selectEndDate, "yyyy-MM-dd");
            selectEndDate = DateUtil.formatDate(endDate);
            queryWrapper.ge("create_time", selectStartDate).le("create_time",selectEndDate).orderByAsc("create_time")
                    .eq("host_id", Convert.toInt(hostId));;
            list = hostTemHumMapper.selectList(queryWrapper);
        }
        for (HostTemHum hostTemHum : list) {
            xNameList.add(hostTemHum.getCreateTime());
            temList.add(hostTemHum.getTemperature());
            humList.add(hostTemHum.getHumidity());
        }
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("xNameList", xNameList);
        returnMap.put("temList", temList);
        returnMap.put("humList", humList);
        return returnMap;

    }
}

